package server

import (
	raftservices "edata-hub/pkg/raft/services"
	workerservices "edata-hub/pkg/server/services"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"os/exec"
	"strings"
)

func (w *Worker) OnHandleCommand(req *workerservices.CommandWorkerReq, server workerservices.WorkerService_OnHandleCommandServer) error {
	//TODO implement me
	resp := &workerservices.CommandWorkerResp{
		Status: 0,
		Msg:    "",
	}
	envs := []string{
		"/usr/local/sbin",
		"/usr/local/bin",
		"/usr/sbin",
		"/usr/bin",
		"/usr/local/edh/jdk/bin",
		"/usr/local/edh/hadoop/bin",
		"/usr/local/edh/hadoop/sbin",
	}
	script := req.Params["script"]
	cmd := exec.Command("sh", "-c", script)
	cmd.Env = append(cmd.Env, fmt.Sprintf("PATH=%s", strings.Join(envs, ":")))
	output, err := cmd.CombinedOutput()
	if err != nil {
		resp.Status = -1
		resp.Msg = fmt.Sprintf("can not execute cmd %s:%s", script, err.Error())
	} else if strings.Contains(string(output), "ERROR") {
		resp.Status = -1
		resp.Msg = string(output)
	} else {
		resp.Status = 1
		resp.Msg = string(output)
	}
	if sendMsgErr := server.Send(resp); sendMsgErr != nil {
		w.Msg.Error("can not send response message %s", sendMsgErr)
	}
	return nil
}

// 创建GRPC客户端
func (w *Worker) CreateRaftGRPCClient() error {
	raftServerAddr := w.Config.RaftConfig.Ip + ":" + w.Config.RaftConfig.RpcPort
	conn, err := grpc.NewClient(raftServerAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		return err
	}
	w.RaftGrpcClient = raftservices.NewRaftServiceClient(conn)
	return nil
}

func (m *Master) CreateWorkerRPCClient(ip string, port string) (workerservices.WorkerServiceClient, error) {
	workerServerAddr := ip + ":" + port
	client, ok := m.WorkerRpcClients[ip]
	if !ok {
		m.RServer.Msg.Info("can not find rpc client to %s,creating...", ip)
		conn, err := grpc.NewClient(workerServerAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
		if err != nil {
			return nil, err
		}
		newClient := workerservices.NewWorkerServiceClient(conn)
		m.WorkerRpcClients[ip] = newClient
		client = newClient
	}
	return client, nil
}
